package leafedbox.utils
{
	import mx.core.UIComponent;
	import mx.effects.Effect;
	import mx.states.State;
	import mx.states.Transition;

	/**
	 * A utility class for working with component states.
	 */
	public class StateUtil
	{
		//--------------------------------------------------------------------------
		// Static methods
		//--------------------------------------------------------------------------

		/**
		 * Creates a <code>State</code> object based with attached transitions.
		 *
		 * @param component  The component to add the state to.
		 * @param name       The state name.
		 * @param basedOn    The state this state is based on.
		 * @param overrides  A list of objects that implement the
		 *                   <code>IOverride</code> interface.
		 *
		 * @return  A <code>State</code> with attached transitions.
		 */
		public static function addState(component:UIComponent, name:Object, basedOn:String, ...overrides):void
		{
			// Convert to array
			if(name is String) {
				name = [name];
			}

			var nameArr : Array = name as Array;

			// Create all states
			for(var i:int=0; i<nameArr.length; i++) {
				var state : State = new State();
				state.name    = nameArr[i];
				state.basedOn = (basedOn != null ? basedOn : "");

				// Copy overrides
				for(var j:int=0; j<overrides.length; j++) {
					state.overrides.push(overrides[j]);
				}

				// Add state
				component.states.push(state);
			}
		} 



		/**
		 * Creates a <code>Transition</code> object.
		 *
		 * @param component  The component to add the state to.
		 * @param name       The state name.
		 * @param basedOn    The state this state is based on.
		 * @param overrides  A list of objects that implement the
		 *                   <code>IOverride</code> interface.
		 *
		 * @return  A <code>Transition</code> object.
		 */
		public static function addTransition(component:UIComponent, fromState:Object, toState:Object, effect:Effect):void
		{
			// Convert to an array.
			if(fromState is String) {
				fromState = [fromState];
			}

			// Convert to an array.
			if(toState is String) {
				toState = [toState];
			}

			// Do a cartesian product of the from-to states.
			var fromStateArr : Array = fromState as Array;
			var toStateArr   : Array = toState as Array;

			for(var i:int=0; i<fromStateArr.length; i++) {
				for(var j:int=0; j<toStateArr.length; j++) {
					var transition : Transition = new Transition();
					transition.fromState = fromStateArr[i];
					transition.toState   = toStateArr[j];
					transition.effect    = effect;
					component.transitions.push(transition);
				}
			}
		}


		/**
		 * An ease of use function to determine whether a value is a base state.
		 *
		 * @return  A boolean stating whether the state is the base state.
		 */
		public static function isBaseState(stateName:String):Boolean
		{
			return !stateName || stateName == "";
		}

	}

}